using Lucene.Net.Documents;
using NopSolutions.NopCommerce.BusinessLogic.Categories;

namespace NopSolutions.NopCommerce.LuceneHelper.Tasks
{
    public class CategoriesUpdateTask : BaseTask<CategoriesUpdateTask>
    {
        #region BaseTask

        public CategoriesUpdateTask()
            : base(0)
        {

        }

        public override void DoTask(IndexManager indexManager, SearchManager searchManager, IndexWriterWrapper indexer)
        {
            foreach (var category in CategoryManager.GetAllCategories(false))
            {
                RecursivelyIndexCategories(category, indexer);
            }
        }

        public override LuceneIndexType IndexType
        {
            get { return LuceneIndexType.Category; }
        }

        public override bool RebuildIndex
        {
            get { return true; }
        }

        #endregion

        #region Helpers

        public void RecursivelyIndexCategories(Category category, IndexWriterWrapper indexer)
        {
            if (category == null)
                return;
            var document = new Document();
            document.Add(new Field("CategoryID", category.CategoryId.ToString(), Field.Store.YES,
                                   Field.Index.NOT_ANALYZED));
            document.Add(new Field("Name", category.Name, Field.Store.YES, Field.Index.ANALYZED));
            var children = CategoryManager.GetAllCategoriesByParentCategoryId(category.CategoryId);
            document.Add(new Field("HasChildren", (children.Count > 0).ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            var parent = category.ParentCategory;
            while (parent != null)
            {
                var parentField = new Field("ParentID", parent.CategoryId.ToString(), Field.Store.NO,
                                            Field.Index.NOT_ANALYZED);
                document.Add(parentField);
                parent = parent.ParentCategory;
            }

            indexer.AddDocument(document);

            foreach (var child in children)
            {
                RecursivelyIndexCategories(child, indexer);
            }
        }

        #endregion
    }
}
